package com.newcapec.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.google.code.kaptcha.Constants;
import com.newcapec.entity.Result;
import com.newcapec.entity.UserInfoEntity;
import com.newcapec.service.UserInfoService;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserInfoCotroller {

    @Autowired
    private UserInfoService userInfoService;

    @PostMapping("/test1")
    public Result test1(@RequestBody UserInfoEntity userInfoEntity){
        System.out.println( userInfoEntity.getUserName());
        Result result = new Result();
        result.setMsg(userInfoEntity.getUserPwd());
        result.setMsg("test");
        return result;
    }

    @GetMapping("/exportExcel")
//    public void exportExcel(HttpServletResponse response) throws IOException {
    public void exportExcel(HttpServletResponse response,UserInfoEntity userInfo) throws IOException {
        //查询数据
//        List<UserInfoEntity> userInfoEntityList = userInfoService.selectAll();
        List<UserInfoEntity> userInfoEntityList = userInfoService.selectAll(userInfo);
        Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams("用户数据", "userinfo", "导出信息"),
                UserInfoEntity.class, userInfoEntityList);

        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("用户信息.xls", "UTF-8"));

        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();


    }


    /**
     * excel 导入
     */
    @RequestMapping(value="/importExcel",method=RequestMethod.POST)
    public Result importExcel(HttpServletRequest request) throws Exception {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Result result = new Result();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(false);
            try {
                List<UserInfoEntity> list = ExcelImportUtil.importExcel(file.getInputStream(), UserInfoEntity.class, params);
                boolean flag = userInfoService.saveBatch(list);
                if(flag){
                    result.setCode(200);
                    result.setMsg("导入成功");
                }else{
                    result.setCode(500);
                    result.setMsg("导入失败");
                }

            } catch (Exception e) {
                e.printStackTrace();
                result.setCode(500);
                result.setMsg("导入失败");

            }
        }
        return result;
    }

    @GetMapping(value = "/selectByPage",produces = "application/json;charset=utf-8")
//    public Result selectByPage(Integer page,  Integer limit){
    public Result selectByPage(Integer page,  Integer limit,UserInfoEntity userInfo){

//        Map<String,Object> data = userInfoService.selectAll(page,limit);
        Map<String,Object> data = userInfoService.selectAll(page,limit,userInfo);
        Result result = new Result();
        result.setCode(200);
        result.setMsg("查询成功");
        result.setData(data);
        return result;
    }

    @PostMapping("/addUser")
    public Result addUser(UserInfoEntity userInfoEntity){
        Result result = new Result();
        boolean flag = userInfoService.addUser(userInfoEntity);
        if(flag){
            result.setCode(200);
            result.setMsg("添加成功");
        }else{
            result.setCode(500);
            result.setMsg("添加失败");
        }

        return result;

    }

    @PostMapping("/deleteUser")
    public Result deleteUser(int[] allUserId){
        Result result = new Result();
        //String[] userIds = request.getParameterValues("allUserId[]");

        boolean flag = userInfoService.deleteUser(allUserId);
        if(flag){
            result.setCode(200);
            result.setMsg("删除成功");
        }else{
            result.setCode(500);
            result.setMsg("删除失败");
        }
        return result;
    }

    @PostMapping("/updateUser")
    public Result updateUser(UserInfoEntity userInfoEntity){
        Result result = new Result();
        boolean flag = userInfoService.update(userInfoEntity);
        if(flag){
            result.setCode(200);
            result.setMsg("更新成功");
        }else{
            result.setCode(500);
            result.setMsg("更新失败");
        }

        return result;

    }


    @GetMapping("/login")
    public Result<UserInfoEntity> login(String userName, String userPwd, String verifyCode, HttpServletRequest request){
        HttpSession session = request.getSession();
        //String sessionVerifyCode = (String) session.getAttribute("googleVerifyCode");
        String sessionVerifyCode = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        Result<UserInfoEntity> result = new Result<>();
        if(!verifyCode.equals(sessionVerifyCode)){

            result.setCode(500);
            result.setMsg("验证码错误");
            return  result;
        }
        UserInfoEntity userInfoEntity = userInfoService.login(userName,userPwd);
        if(userInfoEntity == null){
            result.setCode(500);
            System.out.println(500);
            result.setMsg("用户名或密码错误");
        }else{
            userInfoEntity.setUserPwd("");
            result.setCode(200);
            result.setMsg("登录成功");
            result.setData(userInfoEntity);
        }

        return result;
    }
}
